# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : variable_view.py
# Time       ：2023/8/28 15:07
# Author     ：YangYong
# version    ：python 3.10
# Description：
    orderlines变量视图
"""
from flask import request
from flask_restx import fields

from apis.orderlines import orderlines_ns
from apis.orderlines.models import VariableInstance
from apis.orderlines.schema.variable_schema import VariableInstanceSchema
from public.api_utils.api_decorator import handle_api_error
from public.base_export_excel_view import BaseExportExcelView
from public.base_model import db
from public.base_response import generate_response, MarshalModel
from public.base_view import BaseView, AbstractView

variable_instance = {
    'id': fields.String(description='变量实例ID'),
    'process_id': fields.String(description='流程ID'),
    'process_instance_id': fields.String(description='流程实例ID'),
    'process_name': fields.String(description='流程名称'),
    'variable_key': fields.String(description='变量键'),
    'variable_value': fields.String(description='变量值'),
    'variable_desc': fields.String(description='变量描述信息'),
    'variable_type': fields.String(description='变量类型'),
    'is_cache': fields.Boolean(description='是否缓存', default=False),

}

variable_instance_detail = {
    'process_id': fields.String(description='流程ID'),
    'process_instance_id': fields.String(description='流程实例ID'),
}
variable_instance_marshal = MarshalModel('variable_instance', orderlines_ns)


class VariableInstanceDetailView(AbstractView):
    url = '/variable_instance/detail'

    def __init__(self, *args, **kwargs):
        super(VariableInstanceDetailView, self).__init__(*args, **kwargs)
        self.table_orm = VariableInstance
        self.table_schema = VariableInstanceSchema
        self.form_data = request.args

    @handle_api_error()
    @orderlines_ns.expect(variable_instance_marshal.detail_request(variable_instance_detail))
    @orderlines_ns.marshal_with(variable_instance_marshal.detail_response(variable_instance))
    def get(self):
        """根据流程ID，变量名称获取变量实例"""
        obj = db.session.query(VariableInstance).filter(
            VariableInstance.process_instance_id == self.form_data.get('process_instance_id'),
            VariableInstance.variable_key == self.form_data.get('variable_key')
        ).first()
        info = VariableInstanceSchema().dump(obj)
        return generate_response(info)


class VariableInstanceView(BaseView):
    url = '/variable_instance'

    def __init__(self, *args, **kwargs):
        super(VariableInstanceView, self).__init__(*args, **kwargs)
        self.table_orm = VariableInstance
        self.table_schema = VariableInstanceSchema

    def handle_filter(self):
        for key, val in self.form_data.items():
            if hasattr(self.table_orm, key) and val:
                self.filter.append(getattr(self.table_orm, key) == val)

    @handle_api_error()
    @orderlines_ns.doc(description='获取变量实例详情')
    @orderlines_ns.expect(variable_instance_marshal.list_request(variable_instance))
    @orderlines_ns.marshal_with(variable_instance_marshal.list_response(variable_instance))
    def get(self):
        """获取变量实例详情"""
        return super(VariableInstanceView, self).get()

    @handle_api_error()
    @orderlines_ns.doc(description='创建变量实例')
    @orderlines_ns.expect(variable_instance_marshal.create_request(variable_instance))
    @orderlines_ns.marshal_with(variable_instance_marshal.create_response())
    def post(self):
        """创建变量实例"""
        return super(VariableInstanceView, self).post()

    @handle_api_error()
    @orderlines_ns.doc(description='修改变量实例')
    @orderlines_ns.expect(variable_instance_marshal.update_request(variable_instance))
    @orderlines_ns.marshal_with(variable_instance_marshal.update_response())
    def put(self):
        """修改变量实例"""
        return super(VariableInstanceView, self).put()

    @handle_api_error()
    @orderlines_ns.doc(description='删除变量实例')
    @orderlines_ns.expect(variable_instance_marshal.delete_request())
    @orderlines_ns.marshal_with(variable_instance_marshal.delete_response())
    def delete(self):
        """删除变量实例"""
        return super(VariableInstanceView, self).delete()


class VariableInstanceReportView(BaseExportExcelView):
    url = '/variable_instance/export'

    def __init__(self, *args, **kwargs):
        super(VariableInstanceReportView, self).__init__(*args, **kwargs)
        from datetime import datetime
        self.file_name = f'task_{datetime.now().strftime("%Y-%m-%d")}'
        self.columns = {
            'id': '序号',
            'process_id': '流程id',
            'process_name': '流程名称',
            'variable_key': '变量名称',
            'variable_value': '变量值',
            'variable_desc': '变量描述',
            'variable_type': '变量类型',
            'is_cache': '是否缓存',
        }

    @handle_api_error()
    @orderlines_ns.doc(description='导出变量实例')
    @orderlines_ns.expect(variable_instance_marshal.list_request(variable_instance))
    def post(self):
        """导出变量实例"""
        return super(VariableInstanceReportView, self).post()
